package jmind.core.js;
/***
 * ScriptEngine 解析js
 */
import java.io.InputStream;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import jmind.core.util.DataUtil;
import jmind.core.util.IOUtil;

public class AnalyzeScript extends JavaScript {
	
	public static void main(String[] args){
		AnalyzeScript  script=new AnalyzeScript("reduce.js");
		System.out.println(script.getFunctionContent("a"));
	}
	
	ScriptEngine engine = null;
	public AnalyzeScript(String name){
		try {
			engine = new ScriptEngineManager().getEngineByExtension ("js");
			InputStream in = load(name);
			String body=IOUtil.stream2String(in);
			engine.eval(body);
		} catch (ScriptException e) {
			engine=null ;
			e.printStackTrace();
		}
	
	}

	@Override
	public String getFunctionContent(String functionName) {
		
		try {
			if(engine!=null)
			return(String) engine.eval(functionName+".toString()");
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return DataUtil.EMPTY;
	}

	@Override
	public Object eval(String name) {
		// TODO Auto-generated method stub
		try {
			return engine.eval(name);
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
